<?php
class Users_model extends CI_Model {
  function __construct()
  {
    // Call the Model constructor
    parent::__construct();
  }

  function get_entry($cond) {
    $query = $this->db->get_where('users', $cond, 1);
    return $query->row();
  }

  function get_avatars($limit, $start) {
    return $query = $this->db->select('u.*, COUNT(v.id) as votes')
    ->from('users as u')
    ->join('votes AS v', 'v.uid = u.id', 'left')
    ->where('u.status', 1)
    ->group_by('u.id')
    //->order_by('u.timestamp', 'desc')
    ->order_by('votes', 'desc')
    ->limit($limit, $start)
    ->get();
  }

  function get_admin_avatars($limit, $start) {
    return $query = $this->db->select('u.*, COUNT(v.id) as votes')
    ->from('users as u')
    ->join('votes AS v', 'v.uid = u.id', 'left')
    ->group_by('u.id')
    ->order_by('u.timestamp', 'desc')
    ->limit($limit, $start)
    ->get();
  }

  function get_avatar($user_id) {
    $query = $this->db->select('users.*, COUNT(v.uid) as votes')
    ->from('users')
    ->join('votes AS v', 'users.id = v.uid', 'left')
    ->where('user_id', $user_id)
    ->group_by('users.id')
    ->limit(1)
    ->get();

    if ($query->num_rows() > 0) {
       return $query->row();
    }
    return FALSE;
  }

  // @todo combine this with above if there is some time
  function get_avatar_by_id($id) {
    $query = $this->db->select('users.*, COUNT(v.uid) as votes')
    ->from('users')
    ->join('votes AS v', 'users.id = v.uid', 'left')
    ->where('users.id', $id)
    ->group_by('users.id')
    ->limit(1)
    ->get();

    if ($query->num_rows() > 0) {
       return $query->row();
    }
    return FALSE;
  }

  function total_avatars() {
    return $result = $this->db->select('COUNT(id) as total_avatars')
    ->from('users')
    ->where('status', 1)
    ->limit(1)
    ->get()->row(0)->total_avatars;
  }

  function get_all_entries() {
    return $this->db->select('*')->from('users')->order_by('timestamp', 'desc')->get();
  }

  function insert_entry($data)
  {
    $this->db->insert('users', $data);
    if ($this->db->affected_rows() == '1')
    {
      return TRUE;
    }

    return FALSE;
  }

  function update_entry($aid, $data) {
    $this->db->where('id', $aid);
    $this->db->update('users', $data);
  }

  function drop_avatar($aid) {
    $this->db->delete('users', array('id' => $aid));
  }
}